<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class UserDetailForm extends CMiniyunStatForm
{
	public $id;
	public $name;
	public $password;
	public $passwordConfirm;
	public $email;
	public $nick;
	public $isAdmin;
	public $space;
	public $usedSpace;	public $fileCount;
	public $deviceCount;

	public $avatar;
	public $status;
	public $realName;
	public $phone;
	public $qq;
	public $website;
	public $memo;

	public $oldPassword;
	public $oldEmail;
	public $oldNick;
	public $oldIsAdmin;
	public $oldSpace;
	public $oldRealName;
	public $oldPhone;
	public $oldQq;
	public $oldWebsite;
	public $oldMemo;

	public $statusArray = array("1" => '启用',"0" => '冻结');
	
	public $adminArray = array("0"=>"用户","1"=>"管理员");

	public function init(){
		$this->space = Yii::app()->params["app"]["defaultSpace"];	}
	public function rules()
	{
		return array(
		array('nick', 'length', 'max'=>255),
		array('email', 'length', 'max'=>255),
		array('password', 'length', 'max'=>255),
		array('passwordConfirm', 'length', 'max'=>255),
		array('space', 'numerical'),
		array('isAdmin', 'numerical', 'integerOnly'=>true),
		array('passwordConfirm', 'compare', 'compareAttribute' => 'password'),
		array('qq', 'length', 'max'=>255),
		array('website', 'length', 'max'=>255),
		array('realName', 'length', 'max'=>255),
		array('memo', 'length', 'max'=>255),
		array('status', 'length', 'max'=>255),
		array('phone', 'numerical'),
		);
	}

	public function attributeLabels()
	{
		return array(
        	'name'             => '用户名',
         	'fileCount'        => '文件',
            'nick'             => '昵称',
            'password'         => '用户密码',
            'passwordConfirm' => '确认密码',
            'realName'         => '真实姓名',
            'email'            => '电子邮件',
            'space'            =>'可用空间',
            'isAdmin'          => '赋予管理员权限',
        	'disabled'      => '用户状态',
            'phone'            => '手机',
            'qq'               => 'QQ号码',
            'website'          => '网站',
            'memo'             => '更多备注',
			'deviceCount'      => '激活设备数',
			'status'      => '用户状态',
		);
	}

	
	private function _fillUser($userData){

		$this->name       = $userData->user_name;
		$this->status   = $userData->user_status;
		$this->oldPassword = $userData->user_pass;		if(!isset($this->name)){
			$this->name="";
		}
		if(!isset($this->status)){
			$this->status=0;
		}
	}

	
	private function _fillUserMeta($userMetaData){
		foreach($userMetaData as $index=>$userMetaItem){
			$metaKey = $userMetaItem->meta_key;
			$metaValue = $userMetaItem->meta_value;
			if($metaKey=="avatar"){
				$this->avatar=$metaValue;
			}
			if($metaKey=="email"){
				$this->email=$metaValue;
				$this->oldEmail=$this->email;
			}
			if($metaKey=="nick"){
				$this->nick=$metaValue;
				$this->oldNick=$this->nick;
			}
			if($metaKey=="phone"){
				$this->phone=$metaValue;
				$this->oldPhone=$this->phone;
			}
			if($metaKey=="space"){
				$this->space=(int)$metaValue;
				$this->oldSpace=$this->space;
			}
			if($metaKey=="is_admin"){
				$this->isAdmin=$metaValue;
				$this->oldIsAdmin=$this->isAdmin;
			}
			if($metaKey=="realname"){
				$this->realName=$metaValue;
				$this->oldRealName=$this->realName;
			}
			if($metaKey=="qq"){
				$this->qq=$metaValue;
				$this->oldQq=$this->qq;
			}
			if($metaKey=="website"){
				$this->website=$metaValue;
				$this->oldWebsite=$this->website;
			}
			if($metaKey=="memo"){
				$this->memo=$metaValue;
				$this->oldMemo=$this->memo;
			}
		}
		if(!isset($this->avatar)){
			$this->avatar=Yii::app()->params["defaultAvatar"];
		}
		if(!isset($this->email)){
			$this->email="";
			$this->oldEmail="";
		}
		if(!isset($this->phone)){
			$this->phone="";
			$this->oldPhone="";
		}
		if(!isset($this->isAdmin)){
			$this->isAdmin=false;
			$this->oldIsAdmin=false;
		}
		if(!isset($this->realName)){
			$this->realName="";
			$this->oldRealName="";
		}
		if(!isset($this->qq)){
			$this->qq="";
			$this->oldQq="";
		}
		if(!isset($this->website)){
			$this->website="";
			$this->oldWebsite="";
		}
		if(!isset($this->memo)){
			$this->memo="";
			$this->oldMemo="";
		}
		if(!isset($this->space)){
			$this->space=Yii::app()->params["app"]["defaultSpace"];
			$this->oldSpace=Yii::app()->params["app"]["defaultSpace"];
		}
	}
	
	private function _validateEmail(){
		if(strlen($this->email)>0){
			$validator = new CEmailValidator;
			if($validator->validateValue($this->email)==false){
				$this->addError("email","电子邮件格式不正确");
				return false;
			}
		}
		return true;
	}

	
	public function getData($id)
	{
		$this->id = $id;
		$this->model=User::model()->findByPk($id);
		if(!isset($this->model))
		throw new CHttpException(404,'The requested page does not exist.');

		$this->_fillUser($this->model);

		$metaModel = UserMeta::model()->findAll(array('condition'=>"user_id=$id"));

		$this->_fillUserMeta($metaModel);

		if($this->getScenario()=="show"){						$this->model = new UserFile();
			$this->initData();			$this->_fileFileInfo($id);
			$this->_fillDeviceInfo($id);
		}

	}
	protected   function getInitDataSql()
	{
		$sql = "SELECT DATE(max(created_at)) as endDate,DATE(min(created_at)) as startDate FROM `".$this->model->tableName()."` where user_id=".(int)$this->id;
		return $sql;
	}
	
	public function statChartPie(){
	 $dbCommand = Yii::app()->db->createCommand("SELECT sum(file_size)/(1024*1024) as usedSpace,user_id  FROM `".Yii::app()->params['tablePrefix']."files` where created_at>='".$this->startDate." 00:00:00' and created_at<='".$this->endDate." 23:59:59' and user_id=".(int)$this->id);
	 $data =  $dbCommand->queryAll();
	 foreach($data as $index=>$item){
	 	$this->usedSpace = $item["usedSpace"];
	 }
	 	 	 $charOptions = array(
	  'theme' => 'gray',
	  'title' => array('text' => '使用统计'),
      'tooltip' => array(
			   'formatter' => 'js:function(){ return \'<b>\'+ this.point.name +\'</b>: \'+ this.y +\' M ，占\'+ForDight(this.percentage,1) +\' %\';}' 
			   ),
      'series' => array( 
			   array(
         'type' => 'pie',
         'data' => array(
			   array('已经使用',(int)$this->usedSpace),
			   array('尚未使用',(int)($this->space-$this->usedSpace)),
			   ),
			   )
			   )
			   );
			   return $charOptions;

	}
	
	public function statHistogram(){
		$data = parent::getSampleHistogramData();
		$charOptions = array(
		'theme' => 'gray',
      'title' => array('text' => '文件增长直方图'),
      'xAxis' => array(
         'categories' => array_keys($data)
		),
      'yAxis' => array(
         'title' => array('text' => '文件')
		),
      'series' => array(
		array('name' => '当前文件数', 'data' => array_values($data)),
		)
		);
		return $charOptions;
	}
	
	private function _fileFileInfo($userId){
		if(isset($userId)){
			$this->fileCount = UserFile::model()->count("user_id=? and created_at>='".$this->startDate." 00:00:00' and created_at<='".$this->endDate." 23:59:59'",array($userId));		}else{
			$this->fileCount = 0;
		}
	}
	
	private function _fillDeviceInfo($userId){
		if(isset($userId)){
			$this->deviceCount = UserDevice::model()->count("user_id=? and created_at>='".$this->startDate." 00:00:00' and created_at<='".$this->endDate." 23:59:59'",array($userId));		}else{
			$this->deviceCount = 0;
		}
	}
	
	public function save()
	{
		if($this->validate()){
						if($this->_validateEmail()){
				$user = User::model()->findByPk($this->id);
				if($this->oldPassword!=$this->password){
					$user["user_pass"] = CSecurity::encryPasswd($this->password);
				}
				$user["user_status"] = $this->status;
				$result = $user->save();
								if($this->email !== $this->oldEmail){
										$userMeta= UserMeta::model()->findByAttributes(array('user_id'=>$this->id, 'meta_key'=>'email'));
					if (empty($userMeta))
					{
						$userMeta = new UserMeta();
						$userMeta["user_id"]=$this->id;
						$userMeta["meta_key"]="email";
					}
					$userMeta["meta_value"]=$this->email;
					$userMeta->save();
					unset($userMeta);
				}
				if($this->nick !== $this->oldNick){
										$userMeta= UserMeta::model()->findByAttributes(array('user_id'=>$this->id, 'meta_key'=>'nick'));
					if (empty($userMeta))
					{
						$userMeta = new UserMeta();
						$userMeta["user_id"]=$this->id;
						$userMeta["meta_key"]="nick";

					}
					$userMeta["meta_value"]=$this->nick;
					$userMeta->save();
					unset($userMeta);
				}
				if($this->isAdmin !== $this->oldIsAdmin){
										$isLastAdmin = false;
					if($this->oldIsAdmin=="1"){						$meta = new UserMeta();
						$isLastAdmin = $meta->isLastAdmin($this->id);
					}
					if($isLastAdmin==false){						$userMeta= UserMeta::model()->findByAttributes(array('user_id'=>$this->id, 'meta_key'=>'is_admin'));
						if (empty($userMeta))
						{
							$userMeta = new UserMeta();
							$userMeta["user_id"]=$this->id;
							$userMeta["meta_key"]="is_admin";
						}
						$userMeta["meta_value"]=$this->isAdmin;
						$userMeta->save();
						unset($userMeta);
					}
				}
				if($this->space !== $this->oldSpace){
										$userMeta= UserMeta::model()->findByAttributes(array('user_id'=>$this->id, 'meta_key'=>'space'));
					if (empty($userMeta))
					{
												$userMeta = new UserMeta();
						$userMeta["user_id"]=$this->id;
						$userMeta["meta_key"]="space";
					}
					$userMeta["meta_value"]=$this->space;
					$userMeta->save();
					unset($userMeta);
				}
				if($this->realName !== $this->oldRealName){
										$userMeta= UserMeta::model()->findByAttributes(array('user_id'=>$this->id, 'meta_key'=>'realname'));
					if (empty($userMeta))
					{
						$userMeta = new UserMeta();
						$userMeta["user_id"]=$this->id;
						$userMeta["meta_key"]="realname";

					}
					$userMeta["meta_value"]=$this->realName;
					$userMeta->save();
					unset($userMeta);
				}
				if($this->phone !== $this->oldPhone){
										$userMeta= UserMeta::model()->findByAttributes(array('user_id'=>$this->id, 'meta_key'=>'phone'));
					if (empty($userMeta))
					{
						$userMeta = new UserMeta();
						$userMeta["user_id"]=$this->id;
						$userMeta["meta_key"]="phone";
					}
					$userMeta["meta_value"]=$this->phone;
					$userMeta->save();
					unset($userMeta);
				}
				if($this->qq !== $this->oldQq){
										$userMeta= UserMeta::model()->findByAttributes(array('user_id'=>$this->id, 'meta_key'=>'qq'));
					if (empty($userMeta))
					{
						$userMeta = new UserMeta();
						$userMeta["user_id"]=$this->id;
						$userMeta["meta_key"]="qq";
					}
					$userMeta["meta_value"]=$this->qq;
					$userMeta->save();
					unset($userMeta);
				}
				if($this->website !== $this->oldWebsite){
										$userMeta= UserMeta::model()->findByAttributes(array('user_id'=>$this->id, 'meta_key'=>'website'));
					if (empty($userMeta))
					{
						$userMeta = new UserMeta();
						$userMeta["user_id"]=$this->id;
						$userMeta["meta_key"]="website";
					}
					$userMeta["meta_value"]=$this->website;
					$userMeta->save();
					unset($userMeta);
				}
				if($this->memo !== $this->oldMemo){
										$userMeta= UserMeta::model()->findByAttributes(array('user_id'=>$this->id, 'meta_key'=>'memo'));
					if (empty($userMeta))
					{
						$userMeta = new UserMeta();
						$userMeta["user_id"]=$this->id;
						$userMeta["meta_key"]="memo";
					}
					$userMeta["meta_value"]=$this->memo;
					$userMeta->save();
					unset($userMeta);
				}
				return true;
			}
		}
		return false;
	}
	
	public function statusDetail(){
		if($this->status){
			return "<img src='".Yii::app()->request->baseUrl.Yii::app()->params["iconUserDisabled"]."' style='width:24px'>";
		}else{
			return "<img src='".Yii::app()->request->baseUrl.Yii::app()->params["iconUserEnabled"]."' style='width:24px'>";
		}
	}
}